package com.sims.action;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.opensymphony.xwork2.ActionSupport;

public class CountAction extends ActionSupport {
	private String num1;
	private String num2;

	private double dnum1;
	private double dnum2;

	private double result;

	public String getNum1() {
		return num1;
	}

	public void setNum1(String num1) {
		this.num1 = num1;
	}

	public String getNum2() {
		return num2;
	}

	public void setNum2(String num2) {
		this.num2 = num2;
	}

	public double getResult() {
		return result;
	}

	public void setResult(int result) {
		this.result = result;
	}

	public String add() {
		result = dnum1 + dnum2;
		return SUCCESS;
	}

	public String minus() {
		result = dnum1 - dnum2;
		return SUCCESS;
	}

	public String multiply() {
		result = dnum1 * dnum2;
		return SUCCESS;
	}

	public String divide() {
		if(dnum2==0){
			throw new RuntimeException("除0错误!");
		}
		result = dnum1 / dnum2;
		
		return SUCCESS;
	}

	// 输入验证
	@Override
	public void validate() {
		super.validate();
		if (!isNumeric(num1)) {
			this.addFieldError("num1", "数据1不是数字");
			System.out.println("数据1不是数字");
		} else {
			dnum1 = Double.parseDouble(num1);
		}
		if (!isNumeric(num2)) {
			this.addFieldError("num2", "数据2不是数字");
			System.out.println("数据=2不是数字");
		} else {
			dnum2 = Double.parseDouble(num2);
		}
	}

	// 判断是否是数字
	private boolean isNumeric(String orginal) {
		String regex = "^[-|\\+]?(\\d+|\\d+\\.\\d+)$";
		if (orginal == null || orginal.trim().equals("")) {
			return false;
		}
		Pattern pattern = Pattern.compile(regex);
		Matcher isNum = pattern.matcher(orginal);
		return isNum.matches();
	}

}
